import type { UserConfig, ConfigEnv } from "vite";
import { resolve } from "path";
import { loadEnv } from "vite";
import { wrapperEnv } from "./build/utils";
import pkg from "./package.json";
import moment from "moment";
import vue from "@vitejs/plugin-vue";
// element-plus自动按需引入
// import AutoImport from "unplugin-auto-import/vite";
// import Components from "unplugin-vue-components/vite";
// import { ElementPlusResolver } from "unplugin-vue-components/resolvers";
// 引入外部svg
import SvgIconsPlugin from "vite-plugin-svg-icons";

function pathResolve(dir: string) {
  return resolve(process.cwd(), ".", dir);
}

const { dependencies, devDependencies, name, version } = pkg;

const __APP_INFO__ = {
  pkg: { dependencies, devDependencies, name, version },
  lastBuildTime: moment().format("YYYY-MM-DD HH:mm:ss"),
};

export default ({ command, mode }: ConfigEnv): UserConfig => {
  const root = process.cwd();
  const env = loadEnv(mode, root);
  const isBuild = command === "build";
  const viteEnv = wrapperEnv(env);
  const { VITE_PORT, VITE_PUBLIC_PATH } = viteEnv;

  return {
    base: VITE_PUBLIC_PATH,
    root,
    server: {
      open: true, //启动项目自动弹出浏览器
      host: true,
      port: VITE_PORT,
    },
    define: {
      __INTLIFY_PROD_DEVTOOLS__: false,
      __APP_INFO__: JSON.stringify(__APP_INFO__),
    },
    plugins: [
      vue(),
      // AutoImport({
      //   resolvers: [ElementPlusResolver()],
      // }),
      // Components({
      //   resolvers: [ElementPlusResolver()],
      // }),
      SvgIconsPlugin({
        iconDirs: [resolve(process.cwd(), "src/assets/icons")],
        svgoOptions: isBuild,
        symbolId: "icon-[dir]-[name]",
      }),
    ],
    resolve: {
      alias: [
        {
          find: /\/@\//,
          replacement: pathResolve("src") + "/",
        },
      ],
    },
    css: {
      preprocessorOptions: {
        less: {
          // 设置颜色变量引入路径
          additionalData: '@import "/@/styles/variables.less";',
        },
      },
    },
  };
};
